use darling::FromDeriveInput;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, DeriveInput};

use super::dma;

#[derive(Debug, FromDeriveInput)]
#[darling(attributes(dma_config2))]
struct Attr {
    tx_dma: u8,
    tx_ch: u8,
    rx_dma: u8,
    rx_ch: u8,
    size: u8,
}

pub fn build(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let attr = Attr::from_derive_input(&input).unwrap();

    let tx_init_fn = format_ident!("tx_dma{}_ch{}_init", attr.tx_dma, attr.tx_ch);
    let rx_init_fn = format_ident!("rx_dma{}_ch{}_init", attr.rx_dma, attr.rx_ch);
    let tx_start_fn = format_ident!("tx_dma{}_ch{}_start", attr.tx_dma, attr.tx_ch);
    let rx_start_fn = format_ident!("rx_dma{}_ch{}_start", attr.rx_dma, attr.rx_ch);

    let tx = dma::create_dma(attr.tx_dma, attr.tx_ch, attr.size, "m_to_p".to_string(), &tx_init_fn, &tx_start_fn);
    let rx = dma::create_dma(attr.rx_dma, attr.rx_ch, attr.size, "p_to_m".to_string(), &rx_init_fn, &rx_start_fn);
    let expand = quote! {
        impl #name {
            #tx
            #rx
        }
    };
    expand.into()
}
